/* 
 * File:   Keyboard.cpp
 * Copyright (C) 2008, 2009
 *		Sergio Padrino Recio (PadrinatoR)
 *
 * Created on 8 de septiembre de 2008, 19:51
 *
 * This file is part of BombProject.
 * 
 * BombProject is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
   
 * BombProject is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.

 * You should have received a copy of the GNU General Public License
 * along with BombProject.  If not, see <http://www.gnu.org/licenses/>.
 */

#include "Keyboard.h"
#include <SDL/SDL_keyboard.h>

#define MAX_KEYS 370

/**
 * Constructor.
 * @param index Device index.
 */
Keyboard::Keyboard(Uint16 index) : InputDevice(index){
	
}

/**
 * Destructor.
 */
Keyboard::~Keyboard(){
	
}

/**
 * Inits the keyboard stuff.
 */
void Keyboard::init(){
	mBuffer = new ButtonState[MAX_KEYS];
	mType = DEVICE_KEYBOARD;
	mNumButtons = MAX_KEYS;
	
	memset(mBuffer, 0, sizeof(ButtonState) * MAX_KEYS);
	
	//update();
}

/**
 * Returns a link to a button from a pressed button, and gives information about its device to the method caller.
 * @param button_info Device info to be returned.
 * @return Link to the pressed key.
 */
ButtonState* Keyboard::getLinkFromPressedButton(DeviceButtonInfo& button_info){
	update();
	
	for(Uint16 i = 0; i < mNumButtons; i++){
		//Ignore these keys as they indicates the state of those flags
		if(i==SDLK_NUMLOCK) continue;
		if(i==SDLK_CAPSLOCK) continue;
		if(i==SDLK_SCROLLOCK) continue;
		
		if(mBuffer[i].button_down == 1){
			button_info.button_code = i;
			button_info.device_index = mIndex;
			button_info.device_type = mType;
			
			return &(mBuffer[i]);
		}
	}
	
	return NULL;
}

/**
 * Returns a link to a key from a given button code.
 * @param button_code Button code.
 * @return Link to the specified key.
 */
ButtonState* Keyboard::getLinkFromButtonCode(Uint16 button_code){
	if(button_code >= mNumButtons) return NULL;
	
	return &(mBuffer[button_code]);
}

/**
 * Updates the keyboard's state.
 */
void Keyboard::update(){
	Uint8* new_buffer = SDL_GetKeyState((int*) &mNumButtons);
	
	for(Uint16 i = 0; i < mNumButtons; i++){
		mBuffer[i].button_down = !mBuffer[i].button_held && new_buffer[i];
		mBuffer[i].button_up = mBuffer[i].button_held && !new_buffer[i];
		mBuffer[i].button_held = new_buffer[i];
	}
//	memcpy(mBuffer, , sizeof(Uint8) * mNumButtons);
}

/**
 * Destroys everything.
 */
void Keyboard::destroy(){
	delete mBuffer;
}

